# -*-code=utf-8 -* -
# noinspection PyUnresolvedReferences
import random
import sys
import webbrowser
from concurrent.futures import ThreadPoolExecutor

from PyQt5.QtWidgets import QApplication, QMainWindow

from bilibili import main as getting
from getinfo import main as enrich
from ui1 import Ui_Form

# list1用于储存所得的结果，flag储存是否获取过视频
list1 = []
flag = False

'''接下来是主窗口的类：
iget函数用于把得到的视频号储存到list1中
go函数用于前往所输入视频网站
roll函数用于随机选取网站
'''


class MainForm(QMainWindow, Ui_Form):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)  # 调用父类的__init__函数
        self.setupUi(self)
        # 接下来几句都是把行为和函数连接起来
        self.button1.clicked.connect(self.iget)
        self.button2.clicked.connect(self.go)
        self.sbbutton.clicked.connect(self.roll)

    def iget(self):
        '''
        本函数的作用是把得到的视频号储存到list1中,然后调用enrich函数获取详细信息
        最后输出到text1中
        '''
        global list1
        global flag
        final = f'加载中：\n{"-"*60}'
        list1 = getting()
        for i in list1:
            print(f"已经获取到的视频号:{i['video']}")

        pool = ThreadPoolExecutor(max_workers=8)  # 八线程
        list1 = pool.map(enrich, list1)  # 多线程操作

        for i in list1:
            tmp = i
            final = (final+'\n\n' +
                     f'{tmp["name"]}\n' +
                     f'视频号:{tmp["video"]}\n' +
                     f'作者:{tmp["author"]}\n\n' +
                     f'简介:{tmp["description"]}\n\n' +
                     f'关键词:{tmp["keywords"]}\n\n\n'+'-'*60
                     )

        self.text1.setText(final)  # 输出获取到的东西
        flag = True

    def go(self):
        '''
        本函数的作用是读取文本,然后打开相应网页
        '''
        video = self.lineEdit.text()
        webbrowser.open('https://www.bilibili.com/video/' + video)

    def roll(self):
        '''
        随机抽取视频进行观看
        '''
        if not flag:
            self.textn.setText('请先获取视频号码')
            return
        global list1
        a = self.textn.text()
        if '00' <= a <= '99':
            a = int(a)
        else:
            a = 1
        if a > 20:
            a = 20
            self.textn.setText('输入太多了!!默认给你开20个吧!')
        for j in range(0, a):
            t = int(random.random() * len(list1))
            webbrowser.open(
                'https://www.bilibili.com/video/' + list1[t]["video"])


if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = MainForm()
    myWin.show()
    sys.exit(app.exec_())
